function [ pulseSum ] = sumflaggedpulses( pulseData, flag, dt)
%SUMFLAGGEDPULSES 对带有标志位的分段的脉冲数按段求和
%
% Input Arguments
% # pulseData: 二维矩阵，应含7列，最后1列为标志位
% # flag: 标量，指定针对特定的标志位值求和，若不指定此参数，则针对所有的标志位求和
% # dt: 标量，脉冲数采样周期
%
% Output Arguments
% # pulseSum: 二维矩阵，包含8列，倒数第2列为脉冲数计数（若未输入dt）或本段的采样时间（若已输入dt），倒数第1列为标志位

if nargin < 2
    flag = [];
end
if nargin < 3
    dt = [];
end
[m, n] = size(pulseData);
if (n==7) && (m>0)
    curDataRow = 1;
    curSumRow = 0;
    curFlag = [];
    hasFlagChanged = 0;
    shouldDoSum = 0;
    while curDataRow <= m
        if isempty(curFlag) || (pulseData(curDataRow, 7)~=curFlag)
            hasFlagChanged = 1;
            curFlag = pulseData(curDataRow, 7);
        end
        if hasFlagChanged
            if (isempty(flag) || (curFlag==flag))
                shouldDoSum = 1;
                curSumRow = curSumRow + 1;
                pulseSum(curSumRow, 8) = pulseData(curDataRow, 7);
            else
                shouldDoSum = 0;
            end
            hasFlagChanged = 0;
        end
        if shouldDoSum
            pulseSum(curSumRow, 1:6) = pulseSum(curSumRow, 1:6) + pulseData(curDataRow, 1:6);
            if isempty(dt)
                pulseSum(curSumRow, 7) = pulseSum(curSumRow, 7) + 1;
            else
                pulseSum(curSumRow, 7) = pulseSum(curSumRow, 7) + dt;
            end
        end
        curDataRow = curDataRow + 1;
    end
else
    error('输入参数应包含7列，至少1行');
end
end